package com.cc.filter;

import com.cc.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @program:
 * @ClassName:
 * @description:
 * @author: zgc
 * @date:
 * @Version 1.0
 **/
@Component
@Slf4j
public class Filter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //1. 获取Zuul提供的请求上下文对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        // 获取request对象
        HttpServletRequest request = requestContext.getRequest();
        log.info("1请求方式：{},地址：{}", request.getMethod(), request.getRequestURI());
        if ("/auth/tologin".equals(request.getRequestURI())) {
            return false;
        }
        if ("OPTIONS".equals(request.getMethod())) {
            requestContext.getResponse().setStatus(HttpServletResponse.SC_OK);
            return false;
        }
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = ctx.getRequest();
        //获取response对象
        HttpServletResponse response = ctx.getResponse();
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        }
        //避免中文乱码
        ctx.addZuulResponseHeader("Content-type", "charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        //打印日志
        log.info("2请求方式：{},地址：{}", request.getMethod(), request.getRequestURI());
        String token = request.getParameter("token");
        System.out.println(token + "---------------");
        if (token == null || token.isEmpty()) {
            ctx.setResponseStatusCode(401);
            ctx.setSendZuulResponse(false);
            return JsonResult.error();
            //ctx.setResponseBody("{\"code\":401,\"message\":\"请先登录\"}");
        }
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        // 这句话，一定不能少，否则会有跨域问题

        return null;
    }
}
